import json

from funcall.AbstractFunCall import AbstractFunCall, fun_call_log_debug, funcall_log, FUN_CALL_REMARK

from conf.config import AppConf
from funcall.FuncallInfo import FuncallInfo
from funcalltools.file_utils import fc_write_file, fc_read_file
from funcall.funcall_result import FuncallResult
from funcalltools.json_utils import to_json
from utils.log_utils import log_title


class file_text_read_fun_call(AbstractFunCall):
    def __init__(self):
        self.name = "file_text_read"
        self.description = "按文本格式读取文件,使用UTF-8格式读取"

        work_dir = AppConf['ai']['work_dir']
        # 因为获取当前时间无需输入参数，因此parameters为空字典
        self.parameters = {
            "type": "object",
            "properties": {
                "filename": {
                    "type": "string",
                    "description": f"文件名称,使用文件名全路径,内容存放在返回json的content中,如果文件读取失败,这会在返回json的error中"
                },
                "remark": {
                    "type": "string",
                    "description": FUN_CALL_REMARK
                }
            }
        }
        self.required = [
            "remark",
            "filename",
            "content"
        ]

    def action(self, jsonRoot):
        filename_tmp = jsonRoot['filename']
        funcallInfo = FuncallInfo(description="file_text_read", req_args=filename_tmp)
        funcallInfo.remark=jsonRoot['remark']
        try:
            with open(filename_tmp, 'r',encoding='utf-8') as file:
                content_tmp = file.read()
                funcallResult = FuncallResult(msg="成功", content=content_tmp)
                funcallInfo.log_text=content_tmp
        except Exception as e:
            funcall_log.warning(f"{e}")
            content_tmp=str(e)
            # print(type(content_tmp))
            funcallResult = FuncallResult(msg="", error=content_tmp)
            funcallInfo.log_text=content_tmp
            # print(json.dumps(funcallResult.__dict__))
        fun_call_log_debug(funcallInfo)
        return funcallResult.to_json()


if __name__ == '__main__':
    import logging

    print("setting logging level")
    logging.basicConfig(level=logging.NOTSET)
    logging.debug("asus")
    # 创建一个GetCurrentWeatherFunCall对象
    cw = file_text_read_fun_call()

    # 调用GetCurrentWeatherFunCall对象的call方法
    args = {"filename": "Z:/aiwork/app-sks.yaml"}
    args = {"filename": "Z:\\aiwork\\erp-service\\target\\erp-service-0.0.1-SNAPSHOT.jar"}
    args = {"filename": "Z:\\aiwork\\programme.md"}
    result = cw.call(args)

    # 打印结果
    print(result)
